<template>
  <el-dialog title="选择区域"
             :visible.sync="area"
             width="60%"
             append-to-body>
    <el-tree :data="treeData"
             ref="stree"
             show-checkbox
             node-key="id"
             :props="defaultProps"
             @check-change="handleCheckChange">
    </el-tree>
    <el-row>
      <el-button type="primary"
                 size="mini"
                 @click="emitData">确定</el-button>
    </el-row>
  </el-dialog>
</template>

<script>
import { getArealist } from '@/api/base/goods/seller/area.js';
export default {
  name: "changeArea",
  data () {
    return {
      area: false,
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      checkeddataIds: [],
      checkeddataStr: []
    }
  },
  watch:{
    'area'(e){
      if(!e){
        this.$refs.stree.setCheckedKeys([]);
      }
    },
  },
  created () {
    getArealist().then(res => {
      if (res.data.code == 200) {
        let data = res.data.data;
        let arr = [];
        for (let i of data) {
          let a = {};
          a.id = i.id;
          a.label = i.areaName;
          if (i.provines.length > 0) {
            let chilarr = [];
            for (let j of i.provines) {
              let b = {};
              b.id = j.id;
              b.label = j.areaName;
              if (j.childs.length > 0) {
                let grandchild = [];
                for (let k of j.childs) {
                  let c = {};
                  c.id = k.id;
                  c.label = k.areaName;
                  grandchild.push(c)
                }
                b.children = grandchild;
              } else {
                b.children = [];
              }
              chilarr.push(b)
            }
            a.children = chilarr;
          } else {
            a.children = [];
          }
          arr.push(a);
        }
        this.treeData = arr;
      }
    })
  },
  methods: {
    open () {
      this.area = true;
    },
    setChecked (keys) {
      console.log(keys)
      keys[0] == '' ? this.$refs.stree.setCheckedKeys([]) : this.$nextTick(() => {this.$refs.stree.setCheckedKeys(keys)});
    },
    handleCheckChange () {
      let changeDataObj = this.$refs.stree.getCheckedNodes(true, false);
      this.checkeddataIds = changeDataObj.map(item => {
        return item.id
      })
      this.checkeddataStr = changeDataObj.map(item => {
        return item.label;
      })
    },
    emitData () {
      //发送数据
      this.$emit('citysData', { checkeddataIds: this.checkeddataIds, checkeddataStr: this.checkeddataStr });
      this.area = false;
    }
  },
}
</script>

<style scoped>
</style>